<?php
namespace app\common\model;
use think\Db;
/**
 * 分类模型-GoodsCat先放在shop模块里面，如果将来home模块也要用到其中一些方法，则把这些方法挪到公共common/model里面
 */
class GoodsCat extends Base {
	/**
	 * 列表
	 */
	public function listQuery($parentId = 0,$catType = ''){
		$parentId = $parentId ? $parentId : input('parentId',0);
		$catType = $catType ? $catType : input('catType',-1);
		$where[] = ['dataFlag','=',1];
		$where[] = ['isShow','=',1];
		$where[] = ['parentId','=',$parentId];
		if($catType != -1 and $parentId == 0)$where[] = ['catType','=',$catType];
		$rs = $this->where($where)
			->order('dataSort desc,catId asc')
			->select();
		return $rs;
	}
	/**
	 * 迭代获取下级
	 */
	public function getChild($ids = array(),$pids = array()){
		$result = $this->where("dataFlag=1 and parentId in(".implode(',',$pids).")")->select();
		
		if(count($result)>0){
			$cids = array();
			foreach ($result as $key =>$v){
				$cids[] = $v['catId'];
			}
			$ids = array_merge($ids,$cids);
			return $this->getChild($ids,$cids);
		}else{
			return $ids;
		}
	}
	/**
	 * 根据子分类获取其父级分类-添加商品，调用商品属性和商品规格时会用到getSpecAndAttr，商品添加修改都要用到
	 */
	public function getParentCatIds($id,$data = array()){
		$data[] = $id;
		$parentId = $this->where('catId',$id)->value('parentId');
		if($parentId==0){
			krsort($data);
			return $data;
		}else{
			return $this->getParentCatIds($parentId, $data);
		}
	}
	/**
	 * 获取分类名称-商品属性用-店铺用到，首页个性定制也用到
	 */
	public function getCatTitlesForAttribute($catIdPath){
		if($catIdPath == '')return '';
		$catIds = str_replace("_",",",substr($catIdPath, 0, -1));
		$rs = $this->where("dataFlag=1 and catId in(".$catIds.")")->column('catTitle');
		if(!empty($rs)){
			return implode('→',$rs);
		}
	}
	/**
	 * 面包屑导航
	 * 迭代获取上级
	 * 返回上级数组
	 * php中实现数组反转array_reverse($catTitles);
	 *
	 * 用法
	 * $catTitles = array();
	 * $m = new ArticleCat();
	 * $catTitles = $m->getParents($catTitles,$catId);
	 */
	public function getParents($catTitles = array(),$catId){
		$rs = $this->field("catId,catTitle,parentId")->where("dataFlag=1 and catId=".$catId)->find();
		// dump($rs);
		if(!empty($rs)){
			$catTitles[] = $rs;
			if($rs['parentId']>0){
				return $this->getParents($catTitles,$rs['parentId']);               
			}else{
				return $catTitles;
			}
		}else{
			return $catTitles;
		}
	}
}